<template>
  <div class="rate-wrap">
    <div
      class="rate-item"
      v-for="(width, index) in rateList"
      :key="index"
      :style="{ fontSize: '20px' }"
    >
      <span
        class="rate-item"
        :style="{ width }"
        :class="{ active: width === 0 ? '' : 'active' }"
      ></span>
    </div>
    <span class="rate-text">{{rateTemplate | filterTemplate(rate)}}</span>
  </div>
</template>

<script>
export default {
  name: 'Rate',
  props: {
    rate: {
      type: Number,
      default: 0
    },
    fontSize: {
      type: Number,
      default: 18
    },
    max: {
      type: Number,
      default: 5
    },
    // 每颗星代表多少分
    perRate: {
      type: Number,
      default: 1
    },
    rateTemplate: {
      type: String,
      default: 'value'
    }
  },
  computed: {
    rateList() {
      const list = new Array(this.max).fill(0);
      const maxRate = this.max * this.perRate; // 最大值
      const activeStarCount = this.rate > maxRate
        ? this.max : Math.floor(this.rate / this.perRate); // 亮的星数量
      let index = 0;
      // 亮的星
      for (;index < activeStarCount; index += 1) {
        list[index] = '100%';
      }
      // 半星
      if (index >= this.max) {
        return list;
      }
      // eslint-disable-next-line no-mixed-operators
      list[index] = `${(this.rate - this.perRate * index) / this.perRate * 100}%`;
      return list;
    }
  },
  filters: {
    filterTemplate(value, rate) {
      const re = /value/;
      if (!re.test(value)) {
        return rate;
      }
      return value.replace(re, rate);
    }
  }
};
</script>

<style lang="less" scoped>
  .rate-wrap {
    display: flex;
    align-items: center;
    .rate-item {
      position: relative;
      &::before {
        font-family: element-icons;
        content: '\e797';
        color: rgb(170, 170, 170);
      }
      &.active::before {
        color: rgb(247, 186, 42);
      }
      span {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    }
    .rate-text {
      margin-left: 5px;
      font-size: 12px;
      color: #666;
    }
  }
</style>
